/**
 * 中国可用的地图服务提供商配置
 * 解决在中国访问Cesium Ion服务时的网络问题
 */

import * as Cesium from 'cesium';

export interface MapProviderConfig {
  name: string;
  provider: Cesium.ImageryProvider;
  description: string;
}

/**
 * 高德地图配置 - 使用UrlTemplateImageryProvider
 */
export const createAmapProvider = (): Cesium.ImageryProvider => {
  return new Cesium.UrlTemplateImageryProvider({
    url: 'https://webrd0{s}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}',
    subdomains: ['1', '2', '3', '4'],
    maximumLevel: 18
  });
};

/**
 * 高德地图卫星图配置 - 使用UrlTemplateImageryProvider
 */
export const createAmapSatelliteProvider = (): Cesium.ImageryProvider => {
  return new Cesium.UrlTemplateImageryProvider({
    url: 'https://webst0{s}.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}',
    subdomains: ['1', '2', '3', '4'],
    maximumLevel: 18
  });
};

/**
 * 天地图配置（需要申请密钥）
 */
export const createTiandituProvider = (apiKey: string = ''): Cesium.ImageryProvider => {
  return new Cesium.WebMapTileServiceImageryProvider({
    url: `https://t{s}.tianditu.gov.cn/vec_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={TileMatrix}&TILEROW={TileRow}&TILECOL={TileCol}&tk=${apiKey}`,
    layer: 'vec',
    style: 'default',
    format: 'tiles',
    tileMatrixSetID: 'w',
    subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'],
    maximumLevel: 18
  });
};

/**
 * 百度地图配置
 */
export const createBaiduProvider = (): Cesium.ImageryProvider => {
  return new Cesium.WebMapTileServiceImageryProvider({
    url: 'https://maponline{s}.bdimg.com/tile/?qt=vtile&x={x}&y={y}&z={z}&styles=pl&scaler=1&udt=20200101',
    layer: 'normal',
    style: 'default',
    format: 'image/png',
    tileMatrixSetID: 'default',
    subdomains: ['0', '1', '2', '3'],
    maximumLevel: 18
  });
};

/**
 * OpenStreetMap配置（备用方案）
 */
export const createOSMProvider = (): Cesium.ImageryProvider => {
  return new Cesium.OpenStreetMapImageryProvider({
    url: 'https://tile.openstreetmap.org/',
    maximumLevel: 18
  });
};

/**
 * CartoDB地图配置（支持CORS）
 */
export const createCartoDBProvider = (): Cesium.ImageryProvider => {
  return new Cesium.UrlTemplateImageryProvider({
    url: 'https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png',
    subdomains: ['a', 'b', 'c', 'd'],
    maximumLevel: 18
  });
};

/**
 * Stamen地图配置（支持CORS）
 */
export const createStamenProvider = (): Cesium.ImageryProvider => {
  return new Cesium.UrlTemplateImageryProvider({
    url: 'https://stamen-tiles-{s}.a.ssl.fastly.net/toner/{z}/{x}/{y}{r}.png',
    subdomains: ['a', 'b', 'c', 'd'],
    maximumLevel: 18
  });
};

/**
 * 获取推荐的地图服务提供商列表
 */
export const getRecommendedMapProviders = (): MapProviderConfig[] => {
  return [
    {
      name: '高德地图',
      provider: createAmapProvider(),
      description: '推荐：中国地区访问稳定，道路信息详细'
    },
    {
      name: '高德卫星图',
      provider: createAmapSatelliteProvider(),
      description: '卫星图像，适合查看地形地貌'
    },
    {
      name: 'CartoDB Light',
      provider: createCartoDBProvider(),
      description: '备用：支持CORS，访问稳定'
    },
    {
      name: 'OpenStreetMap',
      provider: createOSMProvider(),
      description: '开源地图服务'
    }
  ];
};

/**
 * 自动选择最佳地图服务
 * 按优先级尝试加载不同的地图服务
 */
export const autoSelectMapProvider = async (): Promise<Cesium.ImageryProvider> => {
  const providers = [
    { name: '高德地图', create: createAmapProvider },
    { name: '高德卫星图', create: createAmapSatelliteProvider },
    { name: 'CartoDB Light', create: createCartoDBProvider },
    { name: 'OpenStreetMap', create: createOSMProvider }
  ];

  for (const providerInfo of providers) {
    try {
      const provider = providerInfo.create();
      console.log(`尝试加载地图服务: ${providerInfo.name}`);
      return provider;
    } catch (error) {
      console.warn(`${providerInfo.name} 加载失败:`, error);
    }
  }

  // 如果所有服务都失败，返回默认的OSM
  console.warn('所有地图服务加载失败，使用默认OpenStreetMap');
  return createOSMProvider();
};

/**
 * 地图服务配置
 */
export const mapConfig = {
  // 默认地图服务优先级
  defaultProvider: 'amap',
  
  // 地图服务配置
  providers: {
    amap: {
      name: '高德地图',
      create: createAmapProvider,
      description: '中国地区推荐使用'
    },
    amapSatellite: {
      name: '高德卫星图',
      create: createAmapSatelliteProvider,
      description: '卫星图像'
    },
    tianditu: {
      name: '天地图',
      create: createTiandituProvider,
      description: '需要申请API密钥'
    },
    baidu: {
      name: '百度地图',
      create: createBaiduProvider,
      description: '百度地图服务'
    },
    osm: {
      name: 'OpenStreetMap',
      create: createOSMProvider,
      description: '开源地图服务'
    }
  }
};
